//
//  CellForYaoWen.m
//  PCAForWar
//
//  Created by dllo on 16/1/24.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "CellForYaoWen.h"
#import "YaoWenCell.h"
#import "ModelForScroll.h"
#import "ModelForYaoWen.h"
#import "UIImageView+WebCache.h"
#import <MJRefresh.h>
#import <DKNightVersion.h>
#import "NetWorkingHandler.h"

#define WEIGHTT [UIScreen mainScreen].bounds.size.width / 375
#define HEIGHTT [UIScreen mainScreen].bounds.size.height / 667

@interface CellForYaoWen () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) UIView *viewOfTableHead;
@property (nonatomic, retain) UIPageControl *page;
@property (nonatomic, retain) NSMutableArray *arrForScroll;
@property (nonatomic, retain) NSTimer *timerForScroll;
@property (nonatomic, retain) UIImageView *imageSc;
@property (nonatomic, retain) NSString *strForShangLa;
@property (nonatomic, assign) NSInteger pageForShangLa;
@property (nonatomic, retain) NSMutableArray *arrLocation;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, assign) BOOL net;
@property (nonatomic, retain) UIButton *buttonTop;

@end

@implementation CellForYaoWen

- (void)dealloc{
    
    _tableViewYaoWen.dataSource = nil;
    _scrollView.delegate = nil;
    
    [_viewOfTableHead release];
    [_scrollView release];
    [_tableViewYaoWen release];
    [_arrForScroll release];
    [_arrForYaowen release];
    [_timerForScroll release];
    [_strForShangLa release];
    [_page release];
    [_buttonTop release];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        self.arrForYaowen = [NSMutableArray array];
        
        // 设置数据默认的页数为第一页
        self.pageForShangLa = 1;
        
        self.strForShangLa = @"Filter=0&page=1&type=1&processID=getNewsList&pageSize=20&";
        
        
        [self createTableView];
        [self handleData];
        // 调用创建ScrollView方法
        
        // 调用下拉刷新
        [self header];
        // 调用上拉刷新
        [self shangLa];
        
        [self Night];
        [self createButtonForTop];
        
    }
    
    return self;
}

#pragma mark 夜间模式
- (void)Night {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
    self.tableViewYaoWen.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
}

#pragma mark  解析数据
- (void)handleData {
    
    [NetWorkingHandler handleDataByStr:@"http://admin.militaryapp.china.com/News/NewsServlet.do" body:self.strForShangLa header:@"application/x-www-form-urlencoded; charset=UTF-8" block:^(id result) {
        
        NSArray *arrDown = [result objectForKey:@"data"];
        
        // 判断  如果没有数据了  不会crash
        if ([arrDown.class isSubclassOfClass:[NSMutableArray class]]) {
            
            for (NSDictionary *dic in arrDown) {
                
                ModelForYaoWen *model = [[ModelForYaoWen alloc] init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.arrForYaowen addObject:model];
                
            }
            
            NSArray *arrUp = [result objectForKey:@"recommendPic"];
            
            self.arrForScroll = [NSMutableArray array];
            
            for (NSDictionary *dic in arrUp) {
                
                ModelForScroll *model = [[ModelForScroll alloc] init];
                
                [model setValuesForKeysWithDictionary:dic];
                
                [self.arrForScroll addObject:model];
            }
            
            [self.arrForScroll addObject:self.arrForScroll.firstObject];
            
            [self.arrForScroll insertObject:[self.arrForScroll objectAtIndex:self.arrForScroll.count - 2] atIndex:0];
            
        }
        
        [self.tableViewYaoWen reloadData];
        
        [self.tableViewYaoWen.mj_footer endRefreshing];
        
        [self createScrollView];
        
        // 调用Page
        [self createPageViewWithFrame:self.scrollView.frame];
    }];
    
}

#pragma mark 添加tableView
- (void)createTableView {
    
    self.tableViewYaoWen = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height) style:UITableViewStylePlain];
    
    [self.contentView addSubview:self.tableViewYaoWen];
    
    // 取消横线
    self.tableViewYaoWen.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableViewYaoWen.dataSource = self;
    
    self.tableViewYaoWen.showsVerticalScrollIndicator = NO;
    
    self.viewOfTableHead = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 230)];
    
    self.tableViewYaoWen.tableHeaderView = self.viewOfTableHead;
    
    [self.tableViewYaoWen registerClass:[YaoWenCell class] forCellReuseIdentifier:@"pool1"];
    
    [_viewOfTableHead release];
    [_tableViewYaoWen release];
}

#pragma mark tableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrForYaowen.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 30) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showButton1" object:nil];
    }
    
    if (indexPath.row == 15) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenButton1" object:nil];
    }
    
    YaoWenCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool1"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ModelForYaoWen *model = [self.arrForYaowen objectAtIndex:indexPath.row];
    
    [cell passModel:model];
    
    cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
    return cell;
    
}

#pragma mark tableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 100;
    
}

#pragma mark 创建轮播图
- (void)createScrollView {
    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width, 230)];
    
    // 创建自动轮播
    [self Action];
    
    // 设置偏移量等
    self.scrollView.contentOffset = CGPointMake(self.tableViewYaoWen.frame.size.width, 0);
    
    self.scrollView.center = self.viewOfTableHead.center;
    
    // 不显示横线
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    self.scrollView.pagingEnabled = YES;
    
    self.scrollView.delegate = self;
    
    // 设置内容尺寸
    self.scrollView.contentSize = CGSizeMake(self.arrForScroll.count * self.contentView.frame.size.width, 0);
    
    [self.viewOfTableHead addSubview:self.scrollView];
    
    for (int i = 0; i < self.arrForScroll.count; i++) {
        
        self.imageSc = [[UIImageView alloc] initWithFrame:CGRectMake(self.tableViewYaoWen.frame.size.width * i, 0, self.tableViewYaoWen.frame.size.width, 230)];
        
        ModelForScroll *modelSc = self.arrForScroll[i];
        
        [self.imageSc sd_setImageWithURL:[NSURL URLWithString:modelSc.PicUrl]placeholderImage:[UIImage imageNamed:@"jiazai.png"]];
        
        [self.scrollView addSubview:self.imageSc];
        
    }
    
    [_scrollView release];
}

#pragma mark 实现轮播图自动播放
- (void)Action {
    
    if (!self.timerForScroll) {
        
        self.timerForScroll = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImageAction) userInfo:nil repeats:YES];
    }
    
}

- (void)changeImageAction {
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x + self.frame.size.width, 0);
        
    } completion:^(BOOL finished) {
        
        [self scrollViewDidEndDecelerating:self.scrollView];
        
        finished = YES;
    }];
}

// 翻页偏移量
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.x == 0) {
        
        [self.scrollView setContentOffset:CGPointMake(self.frame.size.width * (self.arrForScroll.count - 2), 0)];
        
    } if (scrollView.contentOffset.x == self.frame.size.width * (self.arrForScroll.count - 1)) {
        
        [self.scrollView setContentOffset:CGPointMake(self.frame.size.width, 0)];
    }
    
    self.page.currentPage = scrollView.contentOffset.x / self.tableViewYaoWen.frame.size.width - 1;
    
}

#pragma mark 创建page相关
- (void)createPageViewWithFrame:(CGRect)frame{
    
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 0, frame.size.width / 2, 40)];
    
    // 滚动点的中心点
    self.page.center = CGPointMake(frame.size.width / 2, frame.size.height - 20);
    
    [self.viewOfTableHead addSubview:self.page];
    
    // page个数
    self.page.numberOfPages = self.arrForScroll.count - 2;
    
    [_page release];
}

#pragma mark 下拉刷新
- (void)header {
    
    self.strForShangLa = @"Filter=0&page=1&type=1&processID=getNewsList&pageSize=20&";
    
    self.pageForShangLa = 1;
    
    self.tableViewYaoWen.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewAction)];
    
    [self.tableViewYaoWen.mj_header beginRefreshing];
    
}

- (void)loadNewAction {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableViewYaoWen.mj_header endRefreshing];
        
        [self.tableViewYaoWen reloadData];
        
    });
}

#pragma mark 上拉刷新
- (void)shangLa {
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        self.strForShangLa = [NSString stringWithFormat:@"Filter=0&page=%ld&type=1&processID=getNewsList&pageSize=20&", ++self.pageForShangLa];
        
        [self handleData];
        
    }];
    
    self.tableViewYaoWen.mj_footer = footer;
    
}

#pragma mark 创建Top button
- (void)createButtonForTop {
    
    self.buttonTop = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonTop.frame = CGRectMake(self.tableViewYaoWen.frame.size.width - 60, self.tableViewYaoWen.frame.size.width + 20, 30, 30);
    
    [self.contentView addSubview:self.buttonTop];
    
    [self.buttonTop setImage:[UIImage imageNamed:@"Dingbu"] forState:UIControlStateNormal];
    
    self.buttonTop.hidden = YES;
    
    [self.buttonTop addTarget:self action:@selector(TopAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 通知判断出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleShowButton) name:@"showButton1" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleButtonclick) name:@"hiddenButton1" object:nil];
}

- (void)handleButtonclick {
    
    self.buttonTop.hidden = YES;
    
}

- (void)handleShowButton {
    
    self.buttonTop.hidden = NO;
    
}

- (void)TopAction:(UIButton *)button {
    
    self.buttonTop.hidden = YES;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    
    [self.tableViewYaoWen scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionTop animated:YES];
    
}




@end
